const AUTH = require('../../../utils/auth')
import {
  Logs
} from "../../../utils/log";
const logs = new Logs();
import {
  mpId,
  orderTakingTmplIds
} from "../../../utils/config";
import {
  wxJSAPIPayOrder
} from "../../../api/wxPayController";
import {
  getProductById
} from "../../../api/productController"
import {
  placeAnOrder
} from "../../../api/tradeOrderController";
import {
  updateShopCartById
} from "../../../api/shopCartController";
Page({
  data: {
    wxlogin: true,
    addressInfo: '', //地址信息   直接通过地址页面更改上一个页面栈数据
    productDetail: '',
    count: 1,
    id: ''
  },
  onLoad(options) {
    let {
      id
    } = options
    this.setData({
      id: id
    })
    this.getProductById(id)
  },
  onShow() {
    AUTH.checkHasLogined().then(isLogined => {
      console.log('登录状态', isLogined);
      if (isLogined) {
        this.setData({
          wxlogin: true
        })
      } else {
        this.setData({
          wxlogin: false
        })
      }
    })
    this.getMoney()
  },
  /**
   * 产品详情
   */
  async getProductById(productId) {
    let resolve = await getProductById({
      productId: productId
    })
    this.setData({
      productDetail: resolve.data
    })
    this.getMoney()
  },
  /**
   * 关闭弹窗
   */
  afterAuth() {
    this.setData({
      wxlogin: true
    })
  },
  /**
   * 调用微信地址功能
   */
  openAddress() {
    let custId = wx.getStorageSync('custId')
    if (custId) {
      this.setData({
        wxlogin: true
      })
      wx.navigateTo({
        url: '/pages/distributionCenter/address/index',
      })
    } else {
      this.setData({
        wxlogin: false
      })
    }

    // let self = this
    // wx.chooseAddress({
    //   success(res) {
    //     self.setData({
    //       ['addressInfo.cityName']: res.cityName,
    //       ['addressInfo.countyName']: res.countyName,
    //       ['addressInfo.detailInfo']: res.detailInfo,
    //       ['addressInfo.provinceName']: res.provinceName,
    //       ['addressInfo.telNumber']: res.telNumber,
    //       ['addressInfo.userName']: res.userName,
    //     })
    //     console.log(res);
    //   }
    // })
  },
  /**
   * 处理加减法
   */
  handleNum(e) {
    let {
      type
    } = e.currentTarget.dataset
    // 减法 (不为0)
    if (type === 'del') {
      if (this.data.count <= 1) {
        return
      }
      this.data.count--
      this.setData({
        count: this.data.count
      })
    } else if (type === 'add') {
      // 加法 (需要大于库存)
      this.data.count++
      this.setData({
        count: this.data.count
      })
      // if (this.data.count>=库存) {
      //   return
      // }
    } else {
      let value = this.validateNumber(e.detail.value) - 0
      this.setData({
        count: value
      })
    }
    this.updateShopCartById(this.data.id, this.data.count)
    this.getMoney()
  },
  /**
   * 失去焦点
   */
  bindblur(e) {
    let value = this.validateNumber(e.detail.value) - 0
    value = value == 0 ? 1 : value
    this.setData({
      count: value
    })
    this.getMoney()
  },
  validateNumber(val) {
    return val.replace(/\D/g, '')
  },
  /**
   * 支付
   */
  wxPay() {
    let self = this
    // 校验是否有收货地址
    if (!self.data.addressInfo) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }

    self.placeAnOrder()
    // 20240604不添加消息提醒的弹框
    // wx.requestSubscribeMessage({
    //   tmplIds: orderTakingTmplIds,
    //   complete: (res) => {
    //     AUTH.checkHasLogined().then(isCustId => {
    //       if (!isCustId) {
    //         self.setData({
    //           wxlogin: false
    //         })
    //       } else {
    //         self.setData({
    //           wxlogin: true
    //         })
    //         self.placeAnOrder()
    //       }
    //     })
    //   }
    // })


  },

  /**
   * 复购产品下订单
   */
  async placeAnOrder() {
    let self = this
    let custAddressId = self.data.productDetail.custId
    let resolve = await placeAnOrder({
      productId: self.data.productDetail.id,
      custAddressId: self.data.addressInfo.id,
      count: self.data.count
    })
    // 支付
    if (resolve.success) {
      self.wxJSAPIPayOrder(resolve.data)
    }
  },
  /**
   * 根据Id修改购物车
   */
  async updateShopCartById(id, count) {
    let resolve = await updateShopCartById({
      id: id,
      count: count
    })
  },
  /**
   * 封装预下单方法
   */
  async wxJSAPIPayOrder(params) {
    let resolve = await wxJSAPIPayOrder({
      totalFee: this.data.money * 100,
      productDesc: '云上漂支付测试',
      wxPayOutTradeNo: params.wxPayOutTradeNo,
      tradeOrderId: params.id,
      userLoginState: wx.getStorageSync('userLoginState')
    })
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/orders/order-list/index?type=0',
      })
    }, 1500);
  },
  /**
   * 计算价格
   */
  getMoney() {
    let money = null
    money = this.data.count * this.data.productDetail.price
    this.setData({
      money: money
    })
  }

})